package 事物操作;


import java.sql.*;
import java.util.Scanner;

/*
* 转账：A给B转???,SQL不在拼接字符串
* */
public class Transaction3 {
    public static void main(String[] args)  throws Exception{
        String fkf = null;
        String skf = null;
        int rmb = 0;
//        接收用户输入 Scanner
        Scanner sc =new Scanner(System.in);
        System.out.println("请输入本次的转账金额:");
        rmb = sc.nextInt();
        System.out.println("请输入付款方id:");
        fkf = sc.next();
        System.out.println("请输入收款方id:");
        skf = sc.next();
        System.out.println("正在转账" + rmb + "元");
        String url = "jdbc:mysql://10.4.43.109/db_jdbc_demo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "JJ20021686361520jun";
        Connection conn = null;
        PreparedStatement pstmt = null;
//        将Statement换成高级版
//        ResultSet省略,因为Update没有结果集

        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pass);
            String sql1 = "update t_account set money = money - ? where id = ?";
            String sql2 = "update t_account set money = money + ? where id = ?";
//            开启事物
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql1);//预编译的Statemnet对象（高级版）
//            将sql中的？换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,fkf);
            int i = pstmt.executeUpdate();
            pstmt = conn.prepareStatement(sql2);//预编译的Statemnet对象（高级版）
//            将sql中的？换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,skf);
            int j = pstmt.executeUpdate();
            if (i+j==2){
                System.out.println("转账成功");
                conn.commit();
            }else{
                System.out.println("转账失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("转账出现异常");
            try{
                conn.rollback();
            }catch (SQLException ex){
                ex.printStackTrace();
            }
        }finally {
            try {
                pstmt.close();
                conn.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
